package com.example.sp1902.goods;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.example.sp1902.utils.BaseFragment;
import com.example.sp1902.R;
import com.example.sp1902.utils.URLUtils;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品页面碎片
 */
public class GoodsFragment extends BaseFragment {
    ListView typeLv;
    List<TypeBean.DataBean> data;
    TypeAdapter adapter;
    FragmentManager fm;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fm = getChildFragmentManager();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_goods, container, false);
        typeLv = view.findViewById(R.id.frag_goods_lv);
        //数据源
        data = new ArrayList<>();
        //适配器
        adapter = new TypeAdapter(getContext(), data);
        typeLv.setAdapter(adapter);
        //联网
        connectNetwork(URLUtils.allCategory);
        setItemClick();
        return view;
    }
//设置每一项的点击事件
    private void setItemClick() {
        typeLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                adapter.setSelPos(position);//切换效果
                int cid = data.get(position).getId();
                changeFrag(cid);
            }
        });
    }
    //Frament的切换
    private void changeFrag(int cid) {
        GoodsTypeFragment gtFrag = new GoodsTypeFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("cid",cid);
        gtFrag.setArguments(bundle);

        FragmentTransaction tr = fm.beginTransaction();
        tr.replace(R.id.frag_goods_layout,gtFrag);
        tr.commit();
    }

    @Override
    public void onSuccess(String result) {
        //解析数据
        TypeBean bean = new Gson().fromJson(result, TypeBean.class);
        List<TypeBean.DataBean> list = bean.getData();
        data.addAll(list);
        adapter.notifyDataSetChanged();
        //显示右侧第一个数据
        int cid = data.get(0).getId();
        changeFrag(cid);
    }
}
